package com.myhome.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class SecurityUtils {
    private static final String CLIENT_KEY_NAME = "sub";
    private static final String CLIENT_KEY_CREATED = "created";
    @Value("${jwt.secret}")
    private String secret;
    @Value("${jwt.expiration}")
    private Long expiration;

    //通过claims创建token
    private String generateTokenByClaim(Map<String,Object> claims){
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(generateExpirationDate())
                .signWith(SignatureAlgorithm.HS512,secret)
                .compact();
    }

    //获取过期时间
    private Date generateExpirationDate() {
        return new Date(System.currentTimeMillis()+expiration*1000);
    }

    //获取负载
    private Claims getClaimsFromToken(String token){
        Claims claims = null;
        claims = Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
        return claims;
    }

    private Date generateExpirationFromToken(String token){
        Claims claims = getClaimsFromToken(token);
        return claims.getExpiration();
    }

    private boolean isTokenExpired(String token){
        Date expireDate = generateExpirationFromToken(token);
        return expireDate.before(new Date());
    }

    public String getUserNameFromToken(String token){
        String userName = null;
        try {
            Claims claims = getClaimsFromToken(token);
            userName = claims.getSubject();
        } catch (Exception e) {
            userName = null;
        }
        return userName;
    }

    public boolean validateToken(String token, UserDetails userDetails){
        return getUserNameFromToken(token).equals(userDetails.getUsername())&&!isTokenExpired(token);
    }

    public String generateToken(UserDetails userDetails){
        Map<String,Object> claims = new HashMap<>();
        claims.put(CLIENT_KEY_NAME,userDetails.getUsername());
        claims.put(CLIENT_KEY_CREATED,new Date());
        return generateTokenByClaim(claims);
    }

    private boolean isRefresh(String token){
        return isTokenExpired(token);
    }

    public String refresh(String token){
        Claims claims = getClaimsFromToken(token);
        claims.put(CLIENT_KEY_CREATED,new Date());
        return generateTokenByClaim(claims);
    }
}
